package com.cdgeekcamp.redas.recr_page_worker.component;

import com.cdgeekcamp.redas.db.model.Employee;
import com.cdgeekcamp.redas.db.model.EmployeeRepository;
import com.cdgeekcamp.redas.db.model.R_EmployeeCompany;
import com.cdgeekcamp.redas.db.model.R_EmployeeCompanyRepository;
import com.cdgeekcamp.redas.lib.core.RecrPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class EmployeeBuildServiceImpl implements RecrPageBuildService {
    @Autowired
    private EmployeeRepository employees;

    @Autowired
    private R_EmployeeCompanyRepository r_employeeCompanys;

    public Integer build(RecrPage recrPage, Integer... relatedIds) {
        String name = recrPage.getHrName();
        String position = recrPage.getHrPosition();
        Integer companyId = relatedIds[0];
        Integer employeeId = 0;

        // 通过companyId查询公司雇员列表，通过雇员信息姓名与职位对比，判断公司是否存在相同雇员
        for (Optional<R_EmployeeCompany> r_employeeCompanyOpt : r_employeeCompanys.findAllByCompanyId(companyId)) {
            R_EmployeeCompany r_employeeCompany = r_employeeCompanyOpt.get();
            Integer _employeeId = r_employeeCompany.getEmployeeId();
            Optional<Employee> employeeOpt = employees.findById(_employeeId);

            if (employeeOpt.isEmpty()) {
                log.info(String.format("发现无效的雇员编号：%s", _employeeId));
                continue;
            }

            Employee employee = employeeOpt.get();

            // 雇员存在，则不新建
            if ((employee.getName().equals(name)) && (employee.getPosition().equals(position))) {
                employeeId = employee.getId();
                log.info(String.format("雇员：%s，职位： %s，编号为：%s，已经存在......", name, position, employeeId));
                break;
            }

        }

        // 雇员不存在，则新建雇员并绑定到公司
        if (employeeId == 0) {
            Employee employee = employees.save(new Employee(name, position));
            employeeId = employee.getId();
            log.info(String.format("雇员：%s，职位： %s不存在，新建中......", name, position));

            r_employeeCompanys.save(new R_EmployeeCompany(employeeId, companyId));
            log.info(String.format("雇员：%s->公司：%s 关联不存在，新建中......", employeeId, companyId));
        }

        return employeeId;
    }
}
